package com.slkj.shilixiaoyuanapp.ui.teacher.tool.leave;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.slkj.shilixiaoyuanapp.BuildConfig;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.data.LeaveTypeData;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.PeopleEntity;
import com.slkj.shilixiaoyuanapp.entity.BasePickerTypeEntity;
import com.slkj.shilixiaoyuanapp.entity.code.ToolCode;
import com.slkj.shilixiaoyuanapp.entity.code.UiCode;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.ChosePeopleActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.common.adapter.ChosePicAdapter;
import com.slkj.shilixiaoyuanapp.ui.teacher.tool.common.CommonToolHistoryActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.util.StringUtils;
import com.slkj.shilixiaoyuanapp.util.TimeUtils;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.FileUtils;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.NumberEditText;
import com.slkj.shilixiaoyuanapp.view.PickerViewProvider;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHOSE_SPR_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_MAX_SIZW;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_SPAN_COUNT;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.NO_CHOSE;

@RuntimePermissions
@ActivityInfo(layout = R.layout.activity_aplyy_leave, title = "请假", rightHint = "历史记录")
public class AplyyLeaveActivity extends BaseActivity {
    @BindView(R.id.recyc_pic)
    RecyclerView recycerPic;
    ArrayList<String> picPaths = new ArrayList<>();
    ChosePicAdapter adapter;
    public TakePictureUtils takePictureUtils;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tv_spr)
    TextView tvSpr;
    @BindView(R.id.edit_day)
    EditText editDay;
    @BindView(R.id.edit_content)
    NumberEditText editContent;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_now_day_time)
    TextView tvNowDayTime;
    List<Integer> sqrIds = new ArrayList<>();
    private ArrayList<PeopleEntity> peopleEntities = new ArrayList<>();
    private String startTime, endTime;
    private int qjTypeId = NO_CHOSE;
    public static final String tag = "AplyyLeaveActivity";
    Date date_start = null;
    Date date_end = null;

    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        tvUserName.setText(UserRequest.getInstance().getUser().getUser().getUName());
        tvNowDayTime.setText(TimeUtils.getNowNyr());
        recycerPic.setLayoutManager(new GridLayoutManager(this, CHOSE_PIC_SPAN_COUNT));
        adapter = new ChosePicAdapter(picPaths, this);
        recycerPic.setAdapter(adapter);
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override
            public void successful(File outFile) {
                picPaths.add(outFile.getPath());
                adapter.notifyItemInserted(picPaths.size());
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
            }
        });
    }

    @Override
    protected void onRightTitleClick() {
        CommonToolHistoryActivity__JumpCenter.builder(this)
                .setNetToolType(6)
                .setToolType(ToolCode.TOOL_QJ)
                .create().go();
    }

    @OnClick(R.id.tv_up)
    void upData() {

        if (qjTypeId == NO_CHOSE) {
            showToast("请选择请假类型");
            return;
        }

        if (TextUtils.isEmpty(startTime)) {
            showToast("请选择开始时间");
            return;
        }
        if (TextUtils.isEmpty(endTime)) {
            showToast("请选择结束时间");
            return;
        }
        String day = editDay.getText().toString();
        if (TextUtils.isEmpty(day)) {
            showToast("请输入请假时长");
            return;
        }
        String context = editContent.getText();
        if (TextUtils.isEmpty(context)) {
            showToast("请输入请假事由");
            return;
        }
        if (sqrIds.size() == 0) {
            showToast("请选择审批人");
            return;
        }

        UpdataFileUtil.UpImgObservable("auditLeave", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<String> result) {
                        String img = StringUtils.listToString(result);
                        return HttpHeper.get().toolService().addQj(qjTypeId, startTime, endTime, day, context, img, sqrIds.toString());
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true, this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        LoadSuccessAndFailDialog.showSuccess(AplyyLeaveActivity.this,data);
                        clearContent();
                    }
                });


    }

    @OnClick(R.id.layout_chose_pic)
    void chosePic() {
        if (picPaths.size() == CHOSE_PIC_MAX_SIZW) {
            showToast("最多添加" + CHOSE_PIC_MAX_SIZW + "张图片");
            return;
        }
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }

            @Override
            public void chosePhoto() {
                AplyyLeaveActivityPermissionsDispatcher.onAgreePermissionWithPermissionCheck(AplyyLeaveActivity.this);
            }
        });

    }

    @Recipient(tag = tag + CHOSE_SPR_FINSH)
    void onChoseObjFinsh(int code, String info, List<PeopleEntity> peopleEntityList, List<Integer> checkIds) {
        tvSpr.setText(checkIds.size() == 0 ? "" : info);
        sqrIds.clear();
        sqrIds.addAll(checkIds);
        peopleEntities.clear();
        peopleEntities.addAll(peopleEntityList);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
        if (requestCode == UiCode.CHOSE_PIC_CODE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            for (int i = 0; i < mSelected.size(); i++) {
                String filePath = FileUtils.getPathByUri(this, mSelected.get(i));
                picPaths.add(filePath);
            }
            adapter.notifyItemRangeInserted(picPaths.size(), mSelected.size());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AplyyLeaveActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.CAMERA})
    void onAgreePermission() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(CHOSE_PIC_MAX_SIZW - picPaths.size())
                .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID + ".fileprovider"))
                .imageEngine(new GlideEngine())
                .forResult(UiCode.CHOSE_PIC_CODE);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void onDeniedPermission() {
        showToast("读取照片权限获取失败");
    }


    @OnClick(R.id.layout_chose_type)
    public void onLayoutChoseTypeClicked() {
        List<BasePickerTypeEntity> typeEntityList = LeaveTypeData.getInstance().getTypeEntityList();
        PickerViewProvider.getCommonPicker(this, typeEntityList, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvType.setText(typeEntityList.get(options1).getName());
                qjTypeId = options1 + 1;
            }
        }).show();
    }
    @OnClick(R.id.layout_chose_start_time)
    public void onLayoutChoseStartTimeClicked() {
        PickerViewProvider.getDayTimePickerBefor(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                date_start=date;
                startTime = TimeUtils.dateToStr(date);

                tvStartTime.setText(startTime);
                if (date_end!=null&&date_start!=null){
                    editDay.setText(TimeUtils.getGapCount(date_start,date_end)+"");
                }
            }
        },date_end).show();
    }

    @OnClick(R.id.layout_chose_end_time)
    public void onLayoutChoseEndTimeClicked() {
        PickerViewProvider.getDayTimePickerAfter(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                date_end=date;
                endTime = TimeUtils.dateToStr(date);

                tvEndTime.setText(endTime);
                if (date_end!=null&&date_start!=null){
                    editDay.setText(TimeUtils.getGapCount(date_start,date_end)+"");
                }
            }
        },date_start).show();
    }

    @OnClick(R.id.layout_chose_spr)
    public void onLayoutChoseSprClicked() {
        if (peopleEntities.size() == 0) {
            HttpHeper.get().toolService().getCommonSpr(6)
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<ArrayList<PeopleEntity>>(true, this) {
                        @Override
                        public void onCallBackSuccess(ArrayList<PeopleEntity> data) {
                            peopleEntities.addAll(data);
                            ChosePeopleActivity__JumpCenter.builder(AplyyLeaveActivity.this).setTag(tag).setData(peopleEntities).create().go();
                        }
                    });
        } else {
            ChosePeopleActivity__JumpCenter.builder(AplyyLeaveActivity.this).setTag(tag).setData(peopleEntities).create().go();

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }
}
